<?php

/**
 * 微信支付服务类
 *
 * @author hjc19850430
 */
class WxPayService
{

    /**
     * 获得支付配置
     * @param int $wechatId 微信id
     * @param array $orderInfo 订单信息
     */
    public function getPayConf($wechatId, $orderInfo)
    {
        $mWechat = D('Wechat/Wechat');
        $info = $mWechat->getByPk($wechatId);
        if(!$info) {
            return null;
        }
        
        $payData = array(
            'orderName' => $orderInfo['title'], // 订单名称
            'orderSn' => $orderInfo['order_sn'], // 订单编号
            'orderAmount' => $orderInfo['order_amount'], // 订单金额
            'is_special' => $info['is_special']          // 是否是服务商支付，1:是，0:否
        );
        
        if ($info['is_special'] == '1') {
            $data = array(
                'parentAppid' => $info['parent_appid'],			// 母商户ID
                'parentAppsecret' => $info['parent_appsecret'],	// 母商户密钥
                'parentMchId' => $info['parent_mch_id'],		// 母商户商户ID
                'parentKey' => $info['parent_key'],				// 母商户KEY
                'subOpenid' => $orderInfo['openid'],            // 用户在子商户下的微信openid
                'subAppid' => $info['appid'],					// 子商户ID
                'subMchId' => $info['mch_id']                   // 子商户商户ID
            );
        } else {
            $data = array(
                'appId' => $info['appid'],           //appid
                'mchId' => $info['mch_id'],          //商户号
                'parentKey' => $info['parent_key'],    //支付密钥
                'openId' => $orderInfo['openid'],    //openid
            );
        }
        
        $returnData = array_merge($payData, $data);
        return $returnData;
    }
    
    
    /**
     * 普通用户支付
     * @param array $payData
     * @return array
     */
    public function wechatNormalPay($payData)
    {        
        // 组建支付传输数据包
        $notifyUrl = C('site_url') . U('wechat/wechat_pay/notify');
        
        $verifyField = array(
             'appId',   // 商户的appid
             'mchId',   // 商户ID
             'parentKey',   //商户支付密钥
             'openId',  // 用户在子商户下的微信openid
             'orderName', // 订单名称
             'orderSn', // 订单编号
             'orderAmount', // 订单金额
         );
        wLog('verifyField:'.  var_export($verifyField,true), 'wxPayService');
        
        foreach ($verifyField as $value) {
            if (empty($payData[$value])) {
                return array('status' => 'F', 'message' => $value . '不能为空');
            }
        }

        
        //加载微信支付类
        vendor('Wechat.WechatPay');
        wLog('payData:'. var_export($payData,true), 'wxPayService');
        
//        $payData['openId'] = 'oo5X5wrbEANdTa3dIPFAtVL6tn3c';
//        $payData['appId'] = 'wx90d54df25b0bbe14';
//        $payData['mchId'] = '1308558901';
//        $payData['parentKey'] = 'golive20150603zhejianghangzhouxh';
        $cWechatPay = new WechatPay($payData['appId'], $payData['mchId'], $payData['parentKey'], $notifyUrl);
        $cWechatPay->setParameter('openid', $payData['openId']);
        $cWechatPay->setParameter('appid', $payData['appId']);
        $cWechatPay->setParameter('mch_id', $payData['mchId']);        
        $cWechatPay->setParameter("body", $payData['orderName']);
        $cWechatPay->setParameter("out_trade_no", $payData['orderSn']);
        $cWechatPay->setParameter("total_fee", $payData['orderAmount'] * 100);
        $cWechatPay->setParameter("notify_url", $notifyUrl);
        $cWechatPay->setParameter("trade_type", "JSAPI");
        $cWechatPay->setParameter('spbill_create_ip', getIP());
        $prepayData = $cWechatPay->getPrepayId();

        if ($prepayData['status'] == 'S') {
            $prepayId = $prepayData['data'];
        } else {
            return array('status' => 'F', 'message' => $prepayData['message'] ? $prepayData['message'] : '微支付系统繁忙，请联系管理员');
        }
        $cWechatPay->setPrepayId($prepayId);
        $jsApiParameters = $cWechatPay->getParameters();
        
        wLog('jsApiParam:' . var_export($jsApiParameters, true), 'wechatPay');

        return array('status' => 'S', 'data' => $jsApiParameters);
    }


    /**
     * 母商户支付
     * @param array $payData 支付配置
     */
    public function wechatParentPay($payData)
    {
        $verifyField = array(
            'parentAppid',			// 母商户ID
            'parentMchId',			// 母商户商户ID
            'parentKey',			// 母商户KEY
            'subOpenid',			// 用户在子商户下的微信openid
            'subAppid',				// 子商户ID
            'subMchId',				// 子商户商户ID
            'orderName',			// 订单名称
            'orderSn',				// 订单编号
            'orderAmount',			// 订单金额
        );
        foreach($verifyField as $key => $value){
            if(empty($payData[$value])){
                return array('status' => 'F', 'message' => $value . '不能为空');
            }
        }
        // 组建支付传输数据包
        $notifyUrl = C('site_url').U('wechat/wechat_pay/notify');
        vendor('Wechat.WechatPay');
        $cWechatPay = new WechatPay($payData['parentAppid'], $payData['parentMchId'], $payData['parentKey'], $notifyUrl);
        $cWechatPay->setParameter("sub_openid", $payData['subOpenid']);
        $cWechatPay->setParameter("sub_appid", $payData['subAppid']);
        $cWechatPay->setParameter("sub_mch_id", $payData['subMchId']);
        $cWechatPay->setParameter("body", $payData['orderName']);
        $cWechatPay->setParameter("out_trade_no", $payData['orderSn']);
        $cWechatPay->setParameter("total_fee", $payData['orderAmount'] * 100);
        $cWechatPay->setParameter("notify_url", $notifyUrl);
        $cWechatPay->setParameter("trade_type", "JSAPI");
        $prepayData = $cWechatPay->getPrepayId();
        if($prepayData['status'] == 'S'){
            $prepayId = $prepayData['data'];
        }else{
            return array('status' => 'F', 'message' => $prepayData['message'] ? $prepayData['message'] : '微支付系统繁忙，请联系管理员');
        }

        $cWechatPay->setPrepayId($prepayId);
        $jsApiParameters = $cWechatPay->getParameters();
//        print_r($payData['parentAppid'].",".$payData['parentMchId'].",".$payData['parentKey'].",".$prepayId.",".$jsApiParameters);
        wLog('jsApiParam:'.var_export($jsApiParameters,true),'wxPay');

        return array('status' => 'S', 'data' => $jsApiParameters);
    }
}
